package net.gz01.wallet.web.auth;

import java.util.HashSet;

import javax.servlet.http.HttpSession;

import com.jfinal.template.Directive;
import com.jfinal.template.Env;
import com.jfinal.template.expr.ast.Expr;
import com.jfinal.template.expr.ast.ExprList;
import com.jfinal.template.io.Writer;
import com.jfinal.template.stat.Scope;
import com.jfinal.template.stat.ast.StatList;

/**
 * 自定义的jfinal指令：权限，如验证不过，则页面内改指令范围的内容不输出
 */
public class Authority extends Directive{
	
	public static final String MENU_GROUP = "menuGroup";
	public static final String MENU_URL = "menuUrl";
	
	private Expr exprValue;
	
	public void setExprList(ExprList exprList) {
		if(exprList.length() > 0) {
			this.exprValue = exprList.getExprArray()[0];
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public void exec(Env env, Scope scope, Writer writer) {
		HttpSession session = (HttpSession) scope.get("session");
		String sessionName = (String) session.getAttribute("sessionName");
		boolean success = false;
		
		if(exprValue != null){
			String value =  (String) exprValue.eval(scope);
			//a标签带请求链接
			if(value.indexOf("/") > 0) {
				HashSet<String> urlSet = (HashSet<String>) session.getAttribute(sessionName + MENU_URL);
				success = urlSet.contains(value.trim()); 
			}else {
				HashSet<String> groupSet = (HashSet<String>) session.getAttribute(sessionName + MENU_GROUP);
				success = groupSet.contains(value);
			}
		}else{
			HashSet<String> urlSet = (HashSet<String>) session.getAttribute(sessionName + MENU_URL);
			if(stat.getClass().equals(StatList.class)) {
				StatList sl = (StatList) stat;
				StringBuffer sb = new StringBuffer();
				for(int i = 0 ; i < sl.length() ; i++) {
					sb.append(sl.getStat(i).toString());
				}
				success = urlSet.contains(getUrl(sb.toString().trim())); 
			}else {
				success = urlSet.contains(getUrl(stat.toString().trim())); 
			}
		}
		if(success) {
			stat.exec(env, scope, writer);
		}
	}
	
	private String getUrl(String content){
		// 为不影响原有功能逻辑，默认优先使用href
		if(content.contains("href")) {
			content = content.substring(content.indexOf("href") + 6);
			content = content.substring(0,content.indexOf("\""));
			if(content.indexOf("?") > -1) {
				content = content.substring(0,content.indexOf("?"));
			}
			return content;
		}
		// 使用自定义属性link
		content = content.substring(content.indexOf("link") + 6);
		content = content.substring(0,content.indexOf("\""));
		if(content.indexOf("?") > -1) {
			content = content.substring(0,content.indexOf("?"));
		}
		return content;
	}
	
	@Override
	public boolean hasEnd() {
		return true;
	}
	
}
